import axios from 'axios';

// 设置基础URL，实际开发中应该从环境变量获取
const API_BASE_URL = 'http://localhost:8001'; // 修改为8001端口

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
});

const aiService = {
  // 添加baseURL属性以便在其他地方访问
  baseURL: API_BASE_URL,
  
  // 创建知识库
  createWorkspace(slug) {
    return apiClient.post('/workspace/new', { slug });
  },

  // 删除知识库
  deleteWorkspace(slug) {
    return apiClient.delete(`/workspace/${slug}`);
  },

  // 获取知识库列表
  getWorkspaces() {
    return apiClient.get('/workspace');
  },

  // 获取知识库文档列表
  getDocuments(slug) {
    return apiClient.get(`/workspace/${slug}/documents`);
  },

  // 上传文件到知识库
  uploadFile(slug, file) {
    const formData = new FormData();
    formData.append('file', file);
    
    return apiClient.post(`/workspace/${slug}/upload`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  },

  // 普通问答
  askQuestion(question, slug = 'test', online = false, userId = '1') {
    return apiClient.post(`/workspace/${slug}/chat`, {
      question,
      online,
      user_id: userId,
      citation: false,
    });
  },

  // 带引用的问答
  askWithCitation(question, slug = 'test', online = false, userId = '1') {
    return apiClient.post(`/workspace/${slug}/chat/citation`, {
      question,
      online,
      user_id: userId,
      citation: true,
    });
  },

  // 流式问答
  streamQuestion(question, slug = 'test', online = false, userId = '1', onData, onError, onComplete) {
    // 使用EventSource实现SSE (Server-Sent Events)
    const url = new URL(`${API_BASE_URL}/workspace/${slug}/chat/stream`);
    
    // 准备请求体数据
    const data = {
      question,
      online,
      user_id: userId,
      citation: false
    };

    // 创建POST请求的EventSource
    const eventSource = new EventSource(`${url}?data=${encodeURIComponent(JSON.stringify(data))}`);
    
    // 处理消息事件
    eventSource.onmessage = (event) => {
      try {
        if (event.data === '[DONE]') {
          eventSource.close();
          if (onComplete) onComplete();
          return;
        }
        
        const parsedData = JSON.parse(event.data);
        if (onData) onData(parsedData);
      } catch (error) {
        console.error('Error parsing stream data:', error);
        if (onError) onError(error);
      }
    };
    
    // 处理错误
    eventSource.onerror = (error) => {
      console.error('Stream error:', error);
      eventSource.close();
      if (onError) onError(error);
    };
    
    // 返回eventSource以便外部可以控制关闭
    return eventSource;
  },

  // 流式带引用问答
  streamWithCitation(question, slug = 'test', online = false, userId = '1', onData, onError, onComplete) {
    // 使用EventSource实现SSE (Server-Sent Events)
    const url = new URL(`${API_BASE_URL}/workspace/${slug}/chat/citation/stream`);
    
    // 准备请求体数据
    const data = {
      question,
      online,
      user_id: userId,
      citation: true
    };

    // 创建POST请求的EventSource
    const eventSource = new EventSource(`${url}?data=${encodeURIComponent(JSON.stringify(data))}`);
    
    // 处理消息事件
    eventSource.onmessage = (event) => {
      try {
        if (event.data === '[DONE]') {
          eventSource.close();
          if (onComplete) onComplete();
          return;
        }
        
        const parsedData = JSON.parse(event.data);
        if (onData) onData(parsedData);
      } catch (error) {
        console.error('Error parsing stream data:', error);
        if (onError) onError(error);
      }
    };
    
    // 处理错误
    eventSource.onerror = (error) => {
      console.error('Stream error:', error);
      eventSource.close();
      if (onError) onError(error);
    };
    
    // 返回eventSource以便外部可以控制关闭
    return eventSource;
  },

  // 取消流式生成
  cancelStream(userId = '1') {
    return apiClient.post(`/workspace/test/chat/stream/cancel`, { user_id: userId });
  },

  // 模拟联网搜索
  webSearch(question) {
    // 这里使用普通问答接口，但开启联网搜索
    return this.askQuestion(question, 'test', true);
  },

  // 模拟引用模块搜索
  referenceSearch(question) {
    // 使用带引用的问答接口
    return this.askWithCitation(question, 'test', false);
  }
};

export default aiService; 